<?php


/**
 * @category   Ac
 * @package    Application_Model
 * @copyright  Orient Network Ltd
 * @license    Closed
 * @author     SARDS
 */
class Model_Campaign_User extends Ac_Model {

    protected static $_collection = 'campaign';
    protected static $_transcript = array(
        'cid'     => 'campaign_id',
        'uid'     => 'uid', //ramdomly generated
        'user_id' => 'user_id', //existsting user id
        'fn' => 'firstname',
        'ln' => 'lastname',
        'em' => 'email',
        'fb' => 'facebook_name',
        'kac' => 'know_ac',
        'q1' => 'q1',
        'c_dt' => 'created_at',
        'hua' => 'user_agent',
    );

    public function __construct($data = array(), $config = array()) {
        $config['collection'] = 'campaign';
        parent::__construct($data, $config);
    }

    public function preSave()
    {
        if (empty($this->user_agent) && !empty($_SERVER['HTTP_USER_AGENT'])) {
            $this->user_agent = $_SERVER['HTTP_USER_AGENT'];
        }
        
        //prevent bot from logging history
        if (empty($_SERVER['HTTP_USER_AGENT']) || preg_match('#(bot|slurp)#i', $_SERVER['HTTP_USER_AGENT'])) {
            return false;
        }

        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user_id = Zend_Registry::get('loggedin_user')->_id;
            $this->user_id = $user_id;
        } else {
            //generate a unique id and put it in a cookie if it doesn 't exists
            if (empty($_COOKIE['ac_bookmark'])) {
                $uniqid = uniqid('', true);
                setcookie('ac_bookmark', $uniqid, time()+86400*365, "/");
                $_COOKIE['ac_bookmark'] = $uniqid;
            } else {
                $uniqid = $_COOKIE['ac_bookmark'];
            }
            $this->uid = $uniqid;
        }

        parent::preSave();
    }    
    
    public function postSave() 
    {
        //find user or create one
        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
        } elseif ($user = Model_User::one(array('email' => $this->email))) {
            
        }
        
        $new = false;

        if (empty($user)) {
            $new = true;
            $user           = new Model_User();
            $user->email    = $this->email;
            $user->nl = 1;
            $user->username = Model_User::generateUsername($this->email);
            $password = Model_User::getNewPassword();
            $user->password = Model_USer::generatePassword($password);
        }
        $arr = array();
        if(!empty($user->caid)){
            $arr = $user->caid;
        }
        $arr[] = $this->_id;
        $user->caid = $arr;        
        $user->save();
        $user->forceSave();
        
        $this->user_id = $user->_id;
 
        return parent::postSave();
    }
}
